/*
 * Copyright Aduna (http://www.aduna-software.com/) (c) 1997-2007.
 *
 * Licensed under the Aduna BSD-style license.
 */

package edu.tju.commons.collections;

import java.util.ArrayList;
import java.util.EmptyStackException;

/**
 * This class is exactly the same as java.util.Stack except that it isn't
 * synchronized.
 */
public class UnsynchronizedStack<T> extends ArrayList<T> {

	private static final long serialVersionUID = 3359527172604165398L;

	/**
	 * Creates an empty stack.
	 */
	public UnsynchronizedStack() {
	}

	/**
	 * Pushes an item onto the top of this stack.
	 * 
	 * @param item
	 *            The item to be pushed onto this stack.
	 * @return 'item'.
	 */
	public Object push(T item) {
		add(item);
		return item;
	}

	/**
	 * Removes the object at the top of this stack and returns that object as
	 * the value of this function.
	 * 
	 * @return The object at the top of this stack.
	 * @exception EmptyStackException
	 *                If this stack is empty.
	 */
	public T pop() {
		int size = size();
		if (size == 0) {
			throw new EmptyStackException();
		}
		return remove(size - 1);
	}

	/**
	 * Looks at the object at the top of this stack without removing it from the
	 * stack.
	 * 
	 * @return The object at the top of this stack.
	 * @exception EmptyStackException
	 *                If this stack is empty.
	 */
	public T peek() {
		int size = size();
		if (size == 0) {
			throw new EmptyStackException();
		}
		return get(size - 1);
	}

	/**
	 * Tests if this stack is empty.
	 * 
	 * @return true if if this stack contains no items; false otherwise.
	 */
	public boolean empty() {
		return isEmpty();
	}

	/**
	 * Returns the 1-based position where an object is on this stack. If the
	 * object o occurs as an item in this stack, this method returns the
	 * distance from the top of the stack of the occurrence nearest the top of
	 * the stack; the topmost item on the stack is considered to be at distance
	 * 1. The equals method is used to compare o to the items in this stack.
	 * 
	 * @param o
	 *            The desired object.
	 * @return The 1-based position from the top of the stack where the object
	 *         is located; the return value -1 indicates that the object is not
	 *         on the stack.
	 */
	public int search(Object o) {
		int i = lastIndexOf(o);

		if (i >= 0) {
			return size() - i;
		}
		return -1;
	}
}
